<template>
  <section>
    <!--工具条-->
    <!--<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">-->
      <!--<el-form :inline="true" :model="filters">-->
        <!--<el-form-item>-->
          <!--<el-input v-on:keyup.enter.native="getUsers" v-model="filters.per" placeholder="用户名" class="input-with-select">-->
            <!--<el-button slot="append" icon="el-icon-search" v-on:click="getUsers"/>-->
          <!--</el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item style="float: right">-->
          <!--<el-button type="primary" @click="handleAdd" v-if="this.userType=='30'">新增</el-button>-->
        <!--</el-form-item>-->
      <!--</el-form>-->
    <!--</el-col>-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;background:#fff" >
      <el-form :inline="true" :model="filters">
        <el-form-item style="float: right">
          <div v-if="0" style="border:1px solid #5d6ff3;border-radius:25px;background:translate;width:248px;height:32px;font-size: 14px" >
            <input v-model="filters.per"  @keyup.enter.native="getUsers" type="text" style="border:0px;margin-left:13px;width:130px;height:30px;position:absolute;outline:none" placeholder="用户名"  class="input-with-select">
            <img src="../../image/icon_search.png" style="height:32px;float:right" v-on:click="getUsers">
          </div>

          <!-- <el-input style="border:2px solid #5d6ff3;border-radius:25px;background:translate" @keyup.enter.native="getUsers" v-model="filters.mistiness" placeholder="门店名称/地址" class="input-with-select">
            <el-button slot="append" icon="el-icon-search"  />
          </el-input> -->
        </el-form-item>
        <el-form-item style="float: left">
          <el-button type="primary" @click="handleAdd" style="background:#70d6dc;border:0px;">新 增</el-button>
        </el-form-item>
      </el-form>
    </el-col>


    <!--列表-->
    <el-table :data="users" stripe highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <!--<el-table-column type="selection" width="55">-->
      <!--</el-table-column>-->
      <el-table-column type="index" width="200">
      </el-table-column>
      <el-table-column prop="imagePath" label="图片" width="300" sortable>
        <template slot-scope="scope">
          <img :src="scope.row.imagePath" style="width:200px;height:200px;">
        <!-- <i class="el-icon-time"></i> -->
      </template>
      </el-table-column>
      <el-table-column prop="add_time" label="创建时间" width="300" sortable>
      </el-table-column>
      <el-table-column prop="last_updated_time" label="修改时间" width="300" sortable>
      </el-table-column>
      <el-table-column label="操作" width="96"  fixed="right" >
        <template scope="scope">
          <img src="../../image/icon_bianji.png"   @click="handleEdit(scope.$index, scope.row)">
          <img src="../../image/icon_tingyong.png" @click="handleDel(scope.$index, scope.row)" >
          <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">停用</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col  :span="24" class="toolbar" v-if="this.users.length > 0" style="background:#fff">
      <!--<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>-->

      <el-pagination
        v-if="0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[10]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="float: right">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="100px" :rules="editFormRules" ref="editForm">
        <el-form-item label="图片" prop="loginName">
          <img v-if="isShow != 1" :src="addForm.imagePath" width="150px" height="150px"  @click="cancalImage" >
          <el-upload
            v-if="isShow == 1"
            :action="uploadUrl"
            name="aaa"
            list-type="picture-card"
            multiple=false
            :on-preview="bannerhandlePictureCardPreview"
            limit=1
            :on-success="bannerSuccess"
            :on-remove="bannerhandleRemove">
            <i class="el-icon-plus" ></i>
          </el-upload>
          <div style="width:300px;text-align:left;">注:最多上传一张图片，只能上传jpg或者png</div>
          <el-dialog :visible.sync="bannerVisible" size="tiny">
            <img width="100%" :src="bannerUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" status-icon label-width="80px" ref="addForm"
               class="demo-ruleForm">
        <el-form-item label="图片" prop="loginName">
          <el-upload
            :action="uploadUrl"
            name="aaa"
            list-type="picture-card"
            multiple=false
            limit=1
            :on-success="bannerSuccess"
            :on-remove="bannerhandleRemove">
            <i class="el-icon-plus" ></i>
          </el-upload>
          <div style="width:300px;text-align:left;">注:最多上传一张图片，只能上传jpg或者png</div>
          <el-dialog :visible.sync="bannerVisible" size="tiny">
            <img width="100%" :src="bannerUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
  import util from '../../common/js/util'
  import axios from 'axios';
  import qs from 'qs';
  //import NProgress from 'nprogress'
  import {getUserListPage, removeUser, batchRemoveUser, editUser, addUser,baseUrl,basePath} from '../../api/api';

  export default {
    data() {
      var checkPhone = (rule, value, callback) => {
        if(!value){
          callback(new Error('请输入手机号'));
        }
        if (!(/^1[34578]\d{9}$/.test(value))&&value!="") {
          callback(new Error('请输入11位有效的手机号'));
        } else {
          callback();
        }
      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.addForm.checkPassword !== '') {
            this.$refs.addForm.validateField('checkPassword');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.addForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        isShow:0,
        uploadUrl:baseUrl+"resource/upload",
        bannerUrl:'',
        bannerVisible:false,
        bannerUploadVisible:false,
        filters: {
          per: ''
        },
        users: [],
        total: 0,
        page: 1,
        listLoading: false,
        sels: [],//列表选中列
        pageSize: 10,
        currentPage4:1,


        editFormVisible: false,//编辑界面是否显示
        editLoading: false,
        editFormRules: {
          contactPhone: [
            {validator: checkPhone, trigger: 'blur'},
            {required: true, message: '请输入手机号', trigger: 'blur'},
          ],
        },
        //编辑界面数据

        editForm: {
          contactPhone: '',
          loginName: '',
          password: '',
          number: ''
        },

        addFormVisible: false,//新增界面是否显示
        addLoading: false,
        addFormRules: {
          loginName: [
            {required: true, message: '请输入登录名', trigger: 'blur'}
          ],
          password: [
            {validator: validatePass, trigger: 'blur'},
            {required: true, message: '请输入密码', trigger: 'blur'},
          ],
          checkPassword: [
            {validator: validatePass2, trigger: 'blur'},
            {required: true, message: '请再次输入密码', trigger: 'blur'},
          ],
          contactPhone: [
            {validator: checkPhone, trigger: 'blur'},
            {required: true, message: '请输入手机号', trigger: 'blur'},
          ],
        },
        //新增界面数据
        addForm: {
          imagePath:''
        }

      }
    },
    methods: {
      cancalImage:function(){
        this.isShow = 1;
      },
      bannerSuccess:function(response, file, fileList){
        this.addForm.imagePath = response.response.data.aaa;
        this.bannerUrl = response.response.data.aaa;
      },
      bannerhandleRemove(file, fileList) {
        this.addForm.imagePath = "";
        this.bannerUrl = "";
      },
      bannerhandlePictureCardPreview(file) {
       this.bannerUrl = file.url;
       this.bannerVisible = true;
       this.bannerUploadVisible = false;
     },
      //性别显示转换
      formatSex: function (row, column) {
        return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
      },

      handleCurrentChange(val) {
        this.page = val;
        this.getUsers();
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.getUsers();
      },
      //获取用户列表
      getUsers() {

        this.listLoading = true;
        axios({
          method: 'get',
          url:baseUrl+"banner",
          // url:"http://47.92.73.189:8001/api/v2/banner",
          // headers: {'Authorization': sessionStorage.getItem("token")},
        }).then(data => {
          var response = JSON.parse(data.request.response).response;
          this.users = response.data;
          this.listLoading = false;
        }).catch(function (error) {
          console.log(error);
        });

      },
//      axios.delete(basePath+'/api/v2/test/user/'+row.id)
      //停用
      handleDel: function (index, row) {
        this.$confirm('确认删除吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //NProgress.start();
          axios({
            method: 'delete',
            url: baseUrl + 'banner/' + row.id,
            // url:"http://47.92.73.189:8001/api/v2/banner/"+row.id,
          }).then(data => {
            var response = JSON.parse(data.request.response).response;
            if (response.success == 1) {
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
              this.getUsers();
            } else {
              this.$message({
                message: response.return_code,
                type: 'error'
              });
            }
          }).catch(function (error) {
            console.log(error);
          });
        }).catch(() => {

        });
      },


      //显示编辑界面
      handleEdit: function (index, row) {
        this.editFormVisible = true;
        this.addForm.imagePath = row.imagePath;
        this.row = row;
      },
      //显示新增界面
      handleAdd: function () {
        this.addFormVisible = true;
        this.addForm = {
          imagePath:''

        };
      },



      //编辑
      editSubmit: function (row) {
        if(this.addForm.imagePath == "" || this.addForm.imagePath == null || this.addForm.imagePath == undefined){
          this.$message({
            message: '请上传图片!',
            type: 'error'
          });
        }else{
          this.$refs.editForm.validate((valid) => {
            if (valid) {
              this.$confirm('确认提交吗？', '提示', {}).then(() => {
                this.editLoading = true;
                //NProgress.start();
                // let para = Object.assign({}, this.editForm);
  //              axios({
  //                method:'put',
  //                url:
  //              })
                axios({
                  method: 'put',
                  url: baseUrl + 'banner/' + this.row.id,
                  // url:"http://47.92.73.189:8001/api/v2/banner/"+this.row.id,
                  data: this.addForm,
                }).then(data => {
                  var response = JSON.parse(data.request.response).response;
                  if (response.success == 1) {
                    this.$message({
                      message: '修改成功!',
                      type: 'success'
                    });
                    this.editLoading = false;
                    this.$refs['editForm'].resetFields();
                    this.editFormVisible = false;
                    this.getUsers();
                  } else {
                    this.editLoading = false;
                    this.$message({
                      message: response.return_code,
                      type: 'error'
                  });
                  }
                }).catch(function (error) {
                  console.log(error);
                });


                // para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                // editUser(para).then((res) => {
                // 	this.editLoading = false;
                // 	//NProgress.done();
                // 	this.$message({
                // 		message: '提交成功',
                // 		type: 'success'
                // 	});
                // 	this.$refs['editForm'].resetFields();
                // 	this.editFormVisible = false;
                // 	this.getUsers();
                // });


              });
            }
          });
        }

      },
//      axios.post(basePath+'/api/v2/casher',para)
      //新增
      addSubmit: function () {
        if(this.addForm.imagePath == "" || this.addForm.imagePath == null || this.addForm.imagePath == undefined){
          this.$message({
            message: '请上传图片!',
            type: 'error'
          });
        }else{
          this.$refs.addForm.validate((valid) => {
            if (valid) {
              this.$confirm('确认提交吗？', '提示', {}).then(() => {
                this.addLoading = true;
                let para = Object.assign({}, this.addForm);
                console.log(para);
                axios({
                  method: 'post',
                  url: baseUrl + 'banner',
                  // url:"http://47.92.73.189:8001/api/v2/banner",
                  data: para,
                  headers: {'Authorization': sessionStorage.getItem("token")},
                }).then(data => {
                  var response = JSON.parse(data.request.response).response;
                  if (response.success == 1) {
                    this.$message({
                      message: '添加成功!',
                      type: 'success'
                    });
                    this.addLoading = false;
                    this.$refs['addForm'].resetFields();
                    this.addFormVisible = false;
                    this.getUsers();
                  } else {
                    this.addLoading = false;
                    this.$message({
                      message: response.return_code,
                      type: 'error'
                    });

                  }
                }).catch(function (error) {
                  console.log(error);
                  this.getUsers();
                });


                addUser(para).then((res) => {
                  this.addLoading = false;
                  //NProgress.done();
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });
                  this.$refs['addForm'].resetFields();
                  this.addFormVisible = false;
                  this.getUsers();
                });
              });
            }
          });
        }

      },
      selsChange: function (sels) {
        this.sels = sels;
      },
      //批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id).toString();
        this.$confirm('确认删除选中的收银员信息吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          console.log(ids);
          var para = {id__in: JSON.stringify(ids.toString().split(','))}
          axios({
            method: 'delete',
            url: baseUrl + 'url',
            data: para,
            headers: {'Authorization': sessionStorage.getItem("token")},
          }).then(data => {
            this.$message({
              message: '批量删除成功!',
              type: 'success'
            });
            this.getUsers();
          }).catch(function (error) {
            console.log(error);
          });

        }).catch(() => {

        });
      }
    },
    mounted() {
      this.getUsers();
    }
  }

</script>

<style scoped>

</style>
